package com.shadowlight.hero_story.login;

import com.alibaba.fastjson.JSONObject;
import com.shadowlight.hero_story.MysqlSessionFactory;
import com.shadowlight.hero_story.asyncOperation.AsyncOperation;
import com.shadowlight.hero_story.asyncOperation.IAsyncOperation;
import com.shadowlight.hero_story.login.database.IUserEntityDao;
import com.shadowlight.hero_story.login.database.entity.UserEntity;
import com.shadowlight.hero_story.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import redis.clients.jedis.Jedis;

import java.util.function.Consumer;

/**
 * @Description 将登陆和登陆以后的业务拆分到两个线程里面，登陆需要的io操作放到异步线程里面，
 * 获取到登陆用户的信息以后返回给主线程操作登陆以后的业务
 * @Author cz
 * @Date 2022/3/16
 */
@Slf4j
public final class LoginService {

    private static final LoginService LOGIN_SERVICE = new LoginService();

    private LoginService() {
    }

    public static LoginService getInstance() {
        return LOGIN_SERVICE;
    }

    public void updateUserBasicInfo(UserEntity userEntity) {
        if (null == userEntity) {
            return;
        }

        try (Jedis redis = RedisUtil.getRedis()) {
            JSONObject jsonUser = new JSONObject();
            jsonUser.put("id", userEntity.getId());
            jsonUser.put("userName", userEntity.getUserName());
            jsonUser.put("heroAvatar", userEntity.getHeroAvatar() == null ? "Hero_Shaman" : userEntity.getHeroAvatar());

            redis.hset(String.format("User_%s", userEntity.getId()), "BasicInfo", jsonUser.toString());
        }
    }

    public void userLogin(String userName, String password, Consumer<UserEntity> consumer) {

        AsyncOperation.getInstance().process(new IAsyncOperation() {
            UserEntity userEntity;

            @Override
            public void doAsync() {
                if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
                    return;
                }

                try (SqlSession mySqlSession = MysqlSessionFactory.openSession()) {
                    IUserEntityDao userEntityDao = mySqlSession.getMapper(IUserEntityDao.class);
                    userEntity = userEntityDao.getByUserName(userName);
                    if (userEntity != null) {
                        if (!password.equals(userEntity.getPassword())) {
                            log.error("用户密码错误: userName:{}, password:{}", userName, password);
                            userEntity = null;
                            return;
                        }
                    } else {
                        userEntity = new UserEntity(userName, password, "Hero_Shaman");
                        userEntityDao.insertInto(userEntity);
                    }
                    updateUserBasicInfo(userEntity);
                    log.info("用户登陆《=======》{}", JSONObject.toJSONString(userEntity));
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }

            @Override
            public void doFinish() {
                if (consumer != null) {
                    consumer.accept(userEntity);
                }
            }

            @Override
            public int getBindId() {
                return userName.charAt(userName.length() - 1);
            }
        });

    }
}
